package com.gitee.sop.bridge.route;

import com.gitee.sop.gatewaycommon.util.LoadBalanceUtil;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiangj
 * @version 1.0.0
 * @ClassName ZKRule.java
 * @Description TODO
 * @createTime 2022年01月08日 14:29:00
 */
public class ZKRule extends AbstractLoadBalancerRule {

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {

        DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) this.getLoadBalancer();
        String name = loadBalancer.getName(); //服务名
        List<Server> servers = loadBalancer.getAllServers().stream().filter(i->{
            return i.getMetaInfo().getAppName().equals(name);
        }).collect(Collectors.toList());
        if(servers!=null && servers.size()>0){
            return LoadBalanceUtil.chooseByRandom(servers);
        }


        return null;
    }
}
